//
//  Tool.m
//  Eath
//
//  Created by yuhaya on 14-8-24.
//  Copyright (c) 2014年 yuhaya. All rights reserved.
//

#import "Tool.h"
#import "Reachability.h"
#import "AFNoneResponseSerializer.h"
#import <AudioToolbox/AudioToolbox.h>

@implementation Tool

+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

+ (BOOL) setUserSetting:(NSString *)stuid andItem:(NSString *)item andVal:(NSString *)val
{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSDictionary * setting = [userDefaultes dictionaryForKey:@"setting"];
    
    NSMutableDictionary * muSetting = [NSMutableDictionary dictionaryWithDictionary:setting];
    NSDictionary * userConfig = [muSetting objectForKey:stuid];
    NSMutableDictionary * muUserConfig = [NSMutableDictionary dictionaryWithDictionary:userConfig];
    [muUserConfig setObject:val forKey:item];
    [muSetting setObject:muUserConfig forKey:stuid];
    
    [userDefaultes setObject:muSetting forKey:@"setting"];
    return  [userDefaultes synchronize];

}

+ (void) point_notice
{
    NSDate * date = [NSDate date];
    NSString * time_format = [[self class] getDateStringWithDate:date DateFormat:@"HH:mm:ss"];
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSArray * stus = [userDefaultes objectForKey:@"STUS"];
    NSDictionary * setting = [userDefaultes dictionaryForKey:@"setting"];
    for (NSDictionary * tmp in stus) {
        NSString * stu_id = tmp[@"stu_id"];
        NSString * stu_name = tmp[@"name"];
        NSDictionary * userConfig = [setting objectForKey:stu_id];
        if(userConfig != nil){
            NSString * AM_I = [NSString stringWithFormat:@"%@:00",userConfig[@"AM_I"]];
            NSString * AM_O = [NSString stringWithFormat:@"%@:00",userConfig[@"AM_O"]];
            NSString * PM_I = [NSString stringWithFormat:@"%@:00",userConfig[@"PM_I"]];
            NSString * PM_O = [NSString stringWithFormat:@"%@:00",userConfig[@"PM_O"]];
            NSString * NM_I = [NSString stringWithFormat:@"%@:00",userConfig[@"NM_I"]];
            NSString * NM_O = [NSString stringWithFormat:@"%@:00",userConfig[@"NM_O"]];
            
            NSString * notice_string = nil;
            
            if([AM_I isEqualToString:time_format]){
                
                notice_string = @"上午上学时间到了！";
            
            }else if ([AM_O isEqualToString:time_format]){
                
                notice_string = @"上午放学时间到了！";
            
            }else if ([PM_I isEqualToString:time_format]){
                
                notice_string = @"下午上学时间到了！";
            
            }else if ([PM_O isEqualToString:time_format]){
                
                notice_string = @"下午放学时间到了！";
            
            }else if ([NM_I isEqualToString:time_format]){
                
                notice_string = @"晚上上学时间到了！";
            
            }else if ([NM_O isEqualToString:time_format]){
            
                notice_string = @"晚上放学时间到了！";
            }
            
            if(notice_string != nil){
                NSString * msg = [NSString stringWithFormat:@"%@的%@",stu_name,notice_string];
                [[self class] showNotice:msg withSound:[tmp[@"SOUND"] boolValue]  withShake:[tmp[@"SHAKE"] boolValue]];
            }
        }
    }
}

+ (void) showNotice:(NSString *) notice withSound:(BOOL) soundFlag withShake:(BOOL) shakeFlag
{
    UILocalNotification *notification=[[UILocalNotification alloc] init];
    if (notification!=nil) {
        
        NSDate *now=[NSDate new];
        notification.fireDate=[now dateByAddingTimeInterval:2]; //触发通知的时间
        notification.repeatInterval=0; //循环次数，kCFCalendarUnitWeekday一周一次
        
        notification.timeZone=[NSTimeZone defaultTimeZone];
        if(soundFlag){
            notification.soundName = UILocalNotificationDefaultSoundName;
        }
        notification.alertBody = notice;
        notification.alertAction = @"打开";  //提示框按钮
        notification.hasAction = YES; //是否显示额外的按钮，为no时alertAction消失
        
//        notification.applicationIconBadgeNumber = 1; //设置app图标右上角的数字
        
        //下面设置本地通知发送的消息，这个消息可以接受
//        NSDictionary* infoDic = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
//        notification.userInfo = infoDic;
        //发送通知
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        
        if(shakeFlag){
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        }
    }
}

+ (void) cacheStudentId:(NSArray *)data
{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    [userDefaultes setObject:data forKey:@"STUS"];
    [userDefaultes synchronize];
}

+ (NSString *) getUserSetting:(NSString *)stuid andItem:(NSString *)item
{
    NSUserDefaults * userDefaultes = [NSUserDefaults standardUserDefaults];
    NSDictionary * setting = [userDefaultes dictionaryForKey:@"setting"];
    
    if(setting == nil){
        
        return nil;
    }else{
        NSDictionary * userConfig = (NSDictionary *)[setting objectForKey:stuid];
        NSString * val = (NSString *)[userConfig objectForKey:item];
        return val;
    }
}

+ (Boolean) networkStatus
{
    Reachability * netRech = [Reachability reachabilityWithHostName:URL_HOSTNAME];
    if ([netRech isReachable]) {
        return YES;
    }else{
        return NO;
    }
}

+ (void) showMessage:(NSString *)str;
{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

+ (AFHTTPRequestOperationManager *) httpManager
{
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    return manager;
}
//将date时间戳转变成时间字符串
//@paaram   date            用于转换的时间
//@param    formatString    时间格式(yyyy-MM-dd HH:mm:ss)
//@return   NSString        返回字字符如（2012－8－8 11:11:11）
+ (NSString *)getDateStringWithDate:(NSDate *)date
                         DateFormat:(NSString *)formatString
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
    [dateFormat setDateFormat:formatString];
    NSString *dateString = [dateFormat stringFromDate:date];
    return dateString;
}
+ (NSString *)getTimeampWithString:(NSString *)timeString DateFormat:(NSString *)formatString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:formatString];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate* date = [formatter dateFromString:timeString];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    return timeSp;
}
//获取某个时间点所在周的周一日期
+ (NSString *)pre_week_date:(NSDate *)date andFormat:(NSString *)format
{
    NSDateComponents *componets = [[NSCalendar autoupdatingCurrentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
    NSInteger weekday = [componets weekday];
    NSInteger gone_day;
    if(weekday == 1){
        gone_day = 6;
    }else{
        gone_day = weekday -2;
    }
    NSInteger sconds = -gone_day * 60*60*24;
    NSDate *date2 = [NSDate dateWithTimeInterval:sconds sinceDate:date];
    return [Tool getDateStringWithDate:date2 DateFormat:format];
}
//获取某个时间点所在周的上一周周末日期对象
+ (NSDate *)bre_week_date_obj:(NSDate *)date
{
    
    NSDateComponents *componets = [[NSCalendar autoupdatingCurrentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
    NSInteger weekday = [componets weekday];
    NSInteger gone_day;
    
    if(weekday == 1){
        gone_day = 7;
    }else{
        gone_day = weekday - 1;
    }
    NSInteger sconds = - gone_day * 60*60*24;
    NSDate *date2 = [NSDate dateWithTimeInterval:sconds sinceDate:date];
    return date2;
}
//获取某个时间点所在周的下一周周末的日期对象(大于当前时间则已当前时间为最终结果)
+ (NSDate *)next_week_date_obj:(NSDate *)date
{
    NSDateComponents *componets = [[NSCalendar autoupdatingCurrentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
    NSInteger weekday = [componets weekday];
    NSInteger gone_day;
    
    if(weekday == 1){
        gone_day = 7;
    }else{
        gone_day = 8 - weekday + 7;
    }
    NSInteger sconds = gone_day * 60*60*24;
    NSDate *date2 = [NSDate dateWithTimeInterval:sconds sinceDate:date];
    NSDate *now = [NSDate date];
    
    if([date2 compare:now] == NSOrderedAscending){
        return date2;
    }else{
        return now;
    }
}

+ (NSString *)weekBytimeamp:(NSUInteger)timeamp
{
    NSDateFormatter *fmtter =[[NSDateFormatter alloc] init];
    [fmtter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [fmtter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    [fmtter setDateFormat:@"EEE"];
    
    NSString* dayString = [fmtter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeamp]];
    
    if ([dayString hasPrefix:@"Mon"]) {
        return @"周二";
    }
    if ([dayString hasPrefix:@"Tue"]) {
        return @"周三";
    }
    if ([dayString hasPrefix:@"Wed"]) {
        return @"周四";
    }
    if ([dayString hasPrefix:@"Thu"]) {
        return @"周五";
    }
    if ([dayString hasPrefix:@"Fri"]) {
        return @"周六";
    }
    if ([dayString hasPrefix:@"Sat"]) {
        return @"周日";
    }
    if ([dayString hasPrefix:@"Sun"]) {
        return @"周一";
    }
    return @"";
}

+ (void) downloadFile:(NSString *)fileUrl
{
    NSDate * date = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
    NSString *  locationString=[dateFormatter stringFromDate:date];
    NSString * filename = [locationString stringByAppendingString:@".png"];
    
    NSString *path = [[[self class] baseImgPath] stringByAppendingPathComponent:filename];
//    NSLog(@"%@",path);
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFNoneResponseSerializer serializer];
    AFHTTPRequestOperation *op = [manager GET:fileUrl
                                   parameters:nil
                                      success:^(AFHTTPRequestOperation *operation, id responseObject) {
//                                          NSLog(@"successful download to %@", path);
                                      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                                          NSLog(@"Error: %@", error);
                                      }];
    op.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:YES];
//    NSLog(@"TEST");
}

+ (NSNumber *)time_str_num:(NSString *)time
{
    NSString * hours = [time substringWithRange:NSMakeRange(0, [time rangeOfString:@":"].location)];
    NSString * minutes = [time substringFromIndex:[time rangeOfString:@":"].location + 1];
    NSInteger mins = hours.integerValue * 60 + minutes.integerValue;
    return [NSNumber numberWithInteger:mins];
}

+ (NSString *) baseImgPath
{
    NSString * allPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/img"];
    [[self class] creatPath:allPath];
    return allPath;
}

+ (BOOL) creatPath:(NSString *)allPath
{
    if([allPath isEqualToString:@""]){
        
        return YES;
    }else{
        
        NSFileManager * fileManager = [NSFileManager defaultManager];
        BOOL isExit = [fileManager fileExistsAtPath:allPath];
        
        if (isExit) {
            
            return YES;
        }
        
        BOOL bo = [fileManager createDirectoryAtPath:allPath withIntermediateDirectories:YES attributes:nil error:nil];
        
        if (bo) {
            
            return YES;
        }
        return NO;
    }
}


/*邮箱验证 MODIFIED BY HELENSONG*/
+(BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

/*手机号码验证 MODIFIED BY HELENSONG*/
+(BOOL) isValidateMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:mobile];
}

/*车牌号验证 MODIFIED BY HELENSONG*/
+(BOOL) validateCarNo:(NSString*) carNo
{
    NSString *carRegex = @"^[A-Za-z]{1}[A-Za-z_0-9]{5}$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    //NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:carNo];
}


+(float) tableHeight
{
    UIScreen * currentScreen = [UIScreen mainScreen];
//    float height = currentScreen.applicationFrame.size.height - 64 - 20 - 50;
    float height = currentScreen.applicationFrame.size.height;
    return height;
}



@end
